import { showToast } from '@/components/Toast';
import { LocalCache } from '@/utils/front/storage';
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  // @ts-ignore
  categoryList: (globalThis.cates || []) as Category[],
  filtersList: {} as {
    [key: string]: { datakey: string; title: string; value: any; type: string };
  },
  userUniqueKey: 'guest',
  compareList: [] as any[],
  compareMaxNum: 4 as number,
  compareOverMax: false as boolean,
};

const productStore = createSlice({
  name: 'product',
  initialState,
  reducers: {
    initProductState(state, action) {
      Object.assign(state, action.payload);
    },
    setCategoryList(state, action) {
      state.categoryList = action.payload;
    },
    addFiltersList(state, action) {
      state.filtersList = Object.assign({}, state.filtersList, {
        [action.payload.datakey]: { ...action.payload },
      });
    },
    removeFiltersList(state, action) {
      if (!action.payload) {
        state.filtersList = {};
      } else {
        const curFilter = state.filtersList[action.payload];
        if (curFilter) {
          const newList = { ...state.filtersList };
          delete newList[action.payload];
          state.filtersList = newList;
        }
      }
    },
    setCompareList(state, action) {
      state.compareList = action.payload;
      const LCache = LocalCache();
      LCache.set('CPL_' + state.userUniqueKey, action.payload);
    },
    restoreCompareList(state, action) {
      const userKey = action.payload || 'guest';
      state.userUniqueKey = userKey;
      const LCache = LocalCache();
      const cpList = LCache.get<any[]>('CPL_' + userKey);
      if (!cpList) return;
      state.compareList = cpList;
      console.log('==========RESTORE COMPARE=========');
    },
    addCompareList(state, action) {
      if (state.compareList.find(p => p.sku == action.payload.sku)) return;
      if (state.compareList?.length >= state.compareMaxNum) {
        showToast({
          type: 'warning',
          message: 'The compare product list cannot have more than 4 products',
          duration: 2000,
        });
        state.compareOverMax = true;
        return;
      }
      const newList = [...state.compareList, action.payload];
      state.compareList = newList;
      const LCache = LocalCache();
      LCache.set('CPL_' + state.userUniqueKey, newList);
    },
    removeCompareList(state, action) {
      if (!state.compareList.find(p => p.sku == action.payload.sku)) return;
      const newList = state.compareList.filter(
        p => p.sku != action.payload.sku
      );
      state.compareList = newList;
      const LCache = LocalCache();
      LCache.set('CPL_' + state.userUniqueKey, newList);
    },
    setCompareMaxNum(state, action) {
      state.compareMaxNum = action.payload;
    },
    setCompareOverMax(state, action) {
      state.compareOverMax = action.payload;
    },
  },
});

export default productStore;
